var crypto = require('crypto');
var config = require('./alipay_config');
var get = require('./get.js');
var post = require('./post.js');
var raw = function (args) {
  var keys = Object.keys(args);
  keys = keys.sort()
  var newArgs = {};
  keys.forEach(function (key) {
    newArgs[key.toLowerCase()] = args[key];
  });
  var string = '';
  for (var k in newArgs) {
    string += '&' + k + '=' + newArgs[k];
  }
  string = string.substr(1);
  return string;
}
/**
* @synopsis 签名算法 
*
* @param jsapi_ticket 用于签名的 jsapi_ticket
* @param url 用于签名的 url ，注意必须动态获取，不能 hardcode
*
* @returns
*/
var AlipayApi = {
    createNonceStr:function () {
      return Math.random().toString(36).substr(2, 15);
    },
    createTimestamp:function () {
      return parseInt(new Date().getTime() / 1000) + '';
    },
    createTime:function () {
      var date = new Date();
      var seperator1 = "-";
      var seperator2 = ":";
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
          month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
          strDate = "0" + strDate;
      }
      var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
              + " " + date.getHours() + seperator2 + date.getMinutes()
              + seperator2 + date.getSeconds();
      return currentdate;
    },
    //签名sign的统一生成
    public_sign:function(ret){
      var string = raw(ret);
      var key = config.key;
      string = string + '&key='+key;  //key为在微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置      
      var sign_str  = crypto.createHash('md5').update(string,'utf8').digest('hex');      
      return sign_str.toUpperCase();
    },
    // 统一下单接口:https://openapi.alipay.com/gateway.do
    alipay_gateway:function(out_trade_no,cb){
      if (out_trade_no == null || out_trade_no == '') {
          return;
      }
      var url = "https://openapi.alipay.com/gateway.do";
      var path = "/gateway.do";
      var ret = {
            appid: config.appid,
            product_code: 'FAST_INSTANT_TRADE_PAY',            
            total_amount: 88.88,
            subject: "哈哈",//订单主题
            body: "订单描述",//订单描述
            goods_detail: {show_url:"https://www.alipay.com"},//订单详细描述信息
            out_trade_no:out_trade_no
      };
      var sign = this.public_sign(ret);
      ret.sign = sign;
      var data = JSON.stringify(ret);
     // console.log(data);
      post.https_post(data,config.host,config.port,path,function(ret,body){
         console.log(body);
         if (ret == 200 && cb != null){
              cb(body,sign,ret);
         }
      });
    }
    // 退款接口
    
};

module.exports = AlipayApi;

//console.log(AlipayApi.createTime());
// AlipayApi.alipay_gateway("123456",function(body,sign,ret){
//   console.log(sign);
// })



